package net.zoneland.zrdp.web.controller.common;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import net.zoneland.zrdp.common.core.redis.RedisService;
import org.springframework.core.io.UrlResource;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.zoneland.zrdp.common.annotation.Anonymous;
import net.zoneland.zrdp.common.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import net.zoneland.zrdp.common.config.ZonevueConfig;
import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.core.domain.AjaxResult;
import net.zoneland.zrdp.common.utils.file.FileUploadUtils;
import net.zoneland.zrdp.common.utils.file.FileUtils;
import net.zoneland.zrdp.framework.config.ServerConfig;

import static net.zoneland.zrdp.common.constant.Constants.FILE_DOWNLOAD_KEY;

/**
 * 通用请求处理
 *
 * @author zonevue
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private ServerConfig serverConfig;

    @Resource
    private ZonevueConfig zonevueConfig;

    @Resource
    private RedisService redisService;

    private static final String FILE_DELIMETER = ",";


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     * @param response response
     */
    @GetMapping("/download")
    public void fileDownload(final String fileName, final Boolean delete, final HttpServletResponse response) {
        final String realFileName = Instant.now().toEpochMilli() + fileName.substring(fileName.indexOf("_") + 1);
        final String downloadPath = zonevueConfig.getDownloadPath();
        final String filePath = Paths.get(downloadPath + fileName).normalize().toString();
        if (!FileUtils.checkAllowDownload(downloadPath, filePath)) {
            throw new BizException(MessageFormat.format("文件名称({0})非法，不允许下载。 ", fileName));
        }
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, realFileName);
        try {
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (Boolean.TRUE.equals(delete)) {
                FileUtils.deleteFile(filePath);
            }
        } catch (final IOException e) {
            LOGGER.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     * @param file 上传文件
     * @return 上传结果
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(final MultipartFile file) {
        try {
            // 上传文件路径
            final String filePath = zonevueConfig.getUploadPath();
            // 上传并返回新文件名称
            final String fileName = serverConfig.fileAddToken(FileUploadUtils.upload(filePath, file));
            final String url = serverConfig.getUrl() + fileName;
            final AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (final IOException e) {
            LOGGER.error("上传文件失败", e);
            return AjaxResult.error("文件上传失败");
        }
    }

    /**
     * 通用上传请求（多个）
     * @param files 上传文件
     * @return 上传结果
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(final List<MultipartFile> files) {
        try {
            // 上传文件路径
            final String filePath = zonevueConfig.getUploadPath();
            final List<String> urls = new ArrayList<>();
            final List<String> fileNames = new ArrayList<>();
            final List<String> newFileNames = new ArrayList<>();
            final List<String> originalFilenames = new ArrayList<>();
            for (final MultipartFile file : files) {
                // 上传并返回新文件名称
                final String fileName = serverConfig.fileAddToken(FileUploadUtils.upload(filePath, file));
                final String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            final AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (final IOException e) {
            LOGGER.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     * @param resource 资源
     * @param response response
     */
    @GetMapping("/download/resource")
    public void resourceDownload(final String resource, final HttpServletResponse response) {
        // 本地资源路径
        final String localPath = zonevueConfig.getProfile();
        // 数据库资源地址
        final String downloadPath = Paths.get(localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX))
            .normalize().toString();
        if (!FileUtils.checkAllowDownload(localPath, downloadPath)) {
            throw new BizException(MessageFormat.format("资源文件({0})非法，不允许下载。 ", resource));
        }
        // 下载名称
        final String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        try {
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (final Exception e) {
            LOGGER.error("下载文件失败", e);
        }
    }

    /**
     * 获取文件，需要验证token 是否有效.
     * <p>
     * 使用方法： <a href="http://loaclhost:8080/common/xxxxtoken/profile/xxx/xx/filename.jpg">...</a>
     * </p>
     * @param token 用于验证是否可以下载文件
     * @param request request
     * @return 返回文件数据
     */
    @Anonymous
    @GetMapping("/{token}/profile/**")
    public ResponseEntity<org.springframework.core.io.Resource> getResource(@PathVariable final String token,
                                                                            final HttpServletRequest request) {
        // 判断token是否有效
        if (redisService.getCacheString(FILE_DOWNLOAD_KEY + token) == null){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        // 获取请求 URI
        final String requestURI = request.getRequestURI();
        // 去掉 /profile 前缀
        final String filename = StringUtils.substringAfter(requestURI, "/profile/");
        final Path basePath = Paths.get(zonevueConfig.getProfile());
        final Path filePath = basePath.resolve(filename).normalize();
        // 检查规范化后的路径是否以安全的基础路径开头
        if (!FileUtils.checkAllowDownload(basePath.toString(), filePath.toString())) {
            LOGGER.warn("非法访问文件：{}", requestURI);
            return ResponseEntity.notFound().build();
        }
        try {
            final org.springframework.core.io.Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (final MalformedURLException e) {
            LOGGER.error("profile下载文件失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
